// pages/selected_server/selected_server.js
var app = getApp();
var that
var Show = require("../../utils/alert/alert.js"); 
Page({ 
  data: {
    isclick_wx_pay: false, //是否点击微信支付显示微信支付界面，true为点击后要显示支付界面
    pay_msg: null,   //此单的订单号 
    //input默认是1  
    num: 1,
    // 使用data数据对象设置样式名  
    minusStatus: 'disabled',
  
    h:0,
    actionSheetHidden_cat:true,
    my_cat:null,
    index:null, //被选中的第i个服务
    service:[],   //下单的服务
    all_money:0,
    
    showModalStatus: false, //会员支付弹窗是否显示 
    pwd:'',  // 会员支付密码
    islevel:0,  // 是否为会员，0不是 1是会员
    add_other:false, //是否点击添加其他服务，若不点，页面卸载会删除服务
    focus:false,
  },
  onLoad: function (options) {
    that=this
    app.req("get_cat.html", { sessionid: wx.getStorageSync('3rd_session'), "openid": app.data.openid }, function (res) {
      if (res.status == "success") { //获取猫的信息
        that.setData({ my_cat: res.mess });
        that.get_ser_msg(options.ser_id); //根据项目id获取项目的信息
      } else if (res.status == "error") {
        that.get_ser_msg(options.ser_id); //根据项目id获取项目的信息有无猫咪都调用
        app.toast(res.mess)//还未添加猫咪提示
      } else {
        app.modal("错误提示", "网络错误，是否重试？", function (re) {
          if (re) {
            that.onLoad(options)
          }
        })
      }
    })
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          h: res.windowHeight
        });
      }
    }); 
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    app.ispoint = 0;
    that.setData({ islevel: app.data.person_msg_rr.level, over_money: app.data.person_msg_rr.credit2 }) //会员账户余额

    app.req("get_cat.html", { sessionid: wx.getStorageSync('3rd_session'), "openid": app.data.openid }, function (res) { //重新获取猫咪更新猫咪
      console.log(res)
      if (res.status == "success") { //获取猫的信息
        console.log(res.mess)
        console.log(that.data.my_cat)
        if (that.data.my_cat){ 
          if (res.mess.length != that.data.my_cat.length) {//猫咪数量有变动
            for (var j = 0; j < app.data.ser_selected.length; j++) {
              app.data.ser_selected[j].cat = res.mess;
            }
          }
       }else{
          for (var j = 0; j < app.data.ser_selected.length; j++) {
            app.data.ser_selected[j].cat = res.mess;
          }
       }
         
        that.setData({ service: app.data.ser_selected });
        that.setData({ my_cat: res.mess });
        setTimeout(function(){
          that.setData({ bottom: 'bot' });
        },500)
       
        console.log(that.data.service)
    
      } else if (res.status == "error") {
        
          for (var j = 0; j < app.data.ser_selected.length; j++) {
            app.data.ser_selected[j].cat = []; //将所有猫制空
          }
          app.toast_up(res.mess)//还未添加猫咪提示
      } else {
        app.modal("错误提示", "网络错误，是否重试？", function (re) {
          if (re) {
            that.onShow() 
          }
        })
      }
    })
    that.setData({ service: app.data.ser_selected });
    that.setAll_price();//计算总金额
  },
  /**
  * 生命周期函数--监听页面卸载
  */
  onUnload: function () {
    if (!that.data.add_other){
      app.data.ser_selected = []; //将酒店服务制空
    }
  },
  ActionSheet_select: function ()//下方选项取消后即隐藏
  {
    this.setData({actionSheetHidden_cat: true })
  },
  add_cat: function () {//点击添加猫咪，跳转到添加猫咪界面
    wx.navigateTo({
      url: '../cat_mse/cat_mse',
    })
  },
  bindKeyInput:function(e){ //项目备注
    console.log(e.detail.value + "  " + e.target.dataset.idx);
    app.data.ser_selected[e.target.dataset.idx].remark = e.detail.value;
    that.setData({ service: app.data.ser_selected});
  },
  select2:function(e){ //每个项目从所有猫咪中选择猫咪
    console.log(e.currentTarget.id + " " + e.currentTarget.dataset.idx);
    that.data.index = e.currentTarget.dataset.idx //第几个服务
    // app.data.ser_selected[that.data.index].cat[e.currentTarget.id]
    if (app.data.ser_selected[that.data.index].cat[e.currentTarget.id].tuoyang == 0 && app.data.ser_selected[that.data.index].type == 2)    //猫未托养且项目不对未托养猫开放
    {
      Show.alertShow(that, "info", "不对未托养猫开放");
      return;
    }
    // console.log(app.data.ser_selected[that.data.index].cat)
    for (var i = 0; i < app.data.ser_selected[that.data.index].cat.length;i++){
      if (i == e.currentTarget.id){
        app.data.ser_selected[that.data.index].cat[i].sed = 1; //设置这只猫被选中
      }else{
        app.data.ser_selected[that.data.index].cat[i].sed = 0;
      }
    }
   
    
    that.setData({ service: app.data.ser_selected, my_cat: that.data.my_cat});
    that.setAll_price();//计算总金额
    // console.log(app.data.ser_selected[that.data.index].cat[e.currentTarget.id]);
  },
  select: function (e) { //通过下方选择猫咪
    if (that.data.my_cat[e.currentTarget.id].tuoyang == 0 && app.data.ser_selected[that.data.index].type==2)    //猫未托养且项目不对未托养猫开放
    {
      // app.toast_up('不对非托养猫开放')
      Show.alertShow(that, "info", "不对未托养猫开放");
      return;
    }
    console.log(that.data.my_cat[e.currentTarget.id])
    console.log(app.data.ser_selected[that.data.index])
    app.data.ser_selected[that.data.index].cat= that.data.my_cat[e.currentTarget.id]  
    that.setData({ service: app.data.ser_selected });
    that.setData({ actionSheetHidden_cat: true })
    that.setAll_price();//计算总金额
  },
  /* 点击减号 */
  bindMinus: function (e) {
    var idx = e.currentTarget.dataset.idx;
    // 如果大于1时，才可以减  
    if (app.data.ser_selected[idx].ser_num > 1) {
      app.data.ser_selected[idx].ser_num--;
    }
    // 只有大于一件的时候，才能normal状态，否则disable状态  
    var minusStatus = app.data.ser_selected[idx].ser_num <= 1 ? 'disabled' : 'normal';
    // 将数值与状态写回  
    this.setData({
      service: app.data.ser_selected,
      minusStatus: minusStatus
    });
    that.setAll_price();//计算总金额

  },
  /* 点击加号 */
  bindPlus: function (e) {
    var idx = e.currentTarget.dataset.idx;
    // 不作过多考虑自增1  
    app.data.ser_selected[idx].ser_num++;
    // 只有大于一件的时候，才能normal状态，否则disable状态  
    var minusStatus = app.data.ser_selected[idx].ser_num < 1 ? 'disabled' : 'normal';
    // 将数值与状态写回  
    this.setData({
      service: app.data.ser_selected,
      minusStatus: minusStatus
    });
    that.setAll_price();//计算总金额
  },
  /* 输入框事件 */
  bindManual: function (e) {
    var idx = e.currentTarget.dataset.idx;
    var num =parseInt(e.detail.value);
    // 将数值与状态写回 
    this.setData({ num: num });
    console.log(num)
    if (num>0){
       app.data.ser_selected[idx].ser_num = num;
       that.setData({ service: app.data.ser_selected});
       that.setAll_price();//计算总金额
    }
  },
  addother_ser:function(){//点击添加其他项目选择其他项目
    // wx.navigateTo({
    //   url: './select_ser',
    // })
    that.setData({add_other:true});
    wx.navigateBack({
      delta: 1
    })
  },
  select_cat:function(e){//点击添加猫咪时弹出下方选择猫咪栏
    that.data.index=e.currentTarget.dataset.idx
    this.setData({ actionSheetHidden_cat: false })
  },
  delete_care_cat: function (e) {//点击删除选择的项目
    that.data.service.splice(e.currentTarget.dataset.idx,1)  //删除某一项
    app.data.ser_selected.splice(e.currentTarget.dataset.idx, 1)  //删除某一项
    that.setData({ service: that.data.service});
    that.setAll_price();//计算总金额
  },
  up_adv:function(e){       // 点击提交订单跳
    app.data.formid = e.detail.formId;
    if (app.globalData.userInfo.phone == '') {     //没有电话设置电话，有电话就返回
      wx.navigateTo({
        url: '../personal_mse/phone?op=op',
      }); return;
    }
    // console.log(that.data.service)
    for (var i = 0; i < that.data.service.length; i++) {
      var t=0
      for (var j = 0; j < that.data.service[i].cat.length;j++){
        if (that.data.service[i].cat[j].sed==1){
          t = 1
        }
      }
      if (t == 0) { app.toast_up("项目未添加猫咪!");return}

      // if (!that.data.service[i].cat) { //对于已添加猫的
      //   app.toast_up("您尚未添加猫咪!")
      //   return
      // }
    } 
    var msg = []
    for (var i = 0; i < that.data.service.length; i++) {  //msg的顺序不可变，后台以此操作
      msg.push(that.data.service[i].id)   //服务id
      for (var j = 0; j < that.data.service[i].cat.length; j++) {
        if (that.data.service[i].cat[j].sed == 1) {
          msg.push(that.data.service[i].cat[j].id)  //猫咪id
        }
      }
      msg.push(that.data.service[i].ser_num)  //服务次数
      if (that.data.service[i].remark == undefined) { that.data.service[i].remark = "" }
      msg.push(that.data.service[i].remark)   //服务备注

    }

    // if (msg.length < that.data.service.length*4){ 
    //   app.toast_up("项目未添加猫咪!")
    //   return
    // }
    // console.log('kdk' + app.ispoint)
    if (app.ispoint == 1) { return; } else { app.ispoint = 1; }
    app.req("payserver.html", { 'openid': app.data.openid, "ser": msg, "price": that.data.all_money, "vs": app.data.vs,"shop_id":wx.getStorageSync('shop_id') },
      function (res) {
       
        if (res.status == "error") {//版本更新了
          app.ispoint = 0;
          Show.alertShow(that, "info", res.mess)
          return;
        }
        console.log(res.mess);    //调用微信支付接口返回的信息
        that.setData({pay_msg: res.mess});

        if (app.data.person_msg_rr.level > 0) {  //如果是会员，就会员支付
          that.util("open")
          return
        } else { that.wx_pay();} //否则微信支付
       
        // that.setData({ isclick_wx_pay: true });//显示微信支付界面
        // wx.setNavigationBarTitle({title: '确认支付'})
      }, function (res) {
        app.ispoint = 0;
      });
  },

  wx_pay:function(){
    wx.requestPayment(
      {
        'timeStamp': this.data.pay_msg.timeStamp,
        'nonceStr': this.data.pay_msg.nonceStr,
        'package': this.data.pay_msg.package,
        'signType': this.data.pay_msg.signType,
        'paySign': this.data.pay_msg.paySign,
        'success': function (re) {
          app.toast("支付成功！")
          app.data.ser_selected = []; //提交订单后将当前订单制空
          that.setData({ service: []});
          app.orderSign(that.data.all_money, "服务消费",that.data.pay_msg.ordersn);//发送微信模板消息
          setTimeout(function () {
            wx.redirectTo({
              url: '../my_order/ser_order?ordersn=' + that.data.pay_msg.ordersn
            })
          }, 1000)
        },
        'fail': function (re) {
          app.ispoint = 0;
          app.toast_up("支付失败！")
        },
        'complete': function (res) { }
      })
  },
  input_pwd: function (e) {//会员支付
    that.setData({ pwd: e.detail.value.trim() })
    if (that.data.pwd.length == 6 && app.data.pointed == true) {//密码位数够了就判断
      that.setData({ focus: false })
      app.data.pointed = false;   //避免快速点击调用两次方法
      setTimeout(function () { app.data.pointed = true; }, 1500)

      app.req("pay_from_member.html", { "ordersn": that.data.pay_msg.ordersn,"price": that.data.all_money, "pwd": that.data.pwd, "type": 'ser', "openid": app.data.openid,'shop_id':wx.getStorageSync('shop_id')}, function (res) {
        if (res.status == "success") {
          app.toast_up(res.mess)
          that.util('close')//关闭支付弹窗
          app.data.ser_selected = []; //提交订单后将当前订单制空
          that.setData({ service: [], });
          app.get_msg_rr();  //充值成功后刷新个人在人人商城的信息
          app.orderSign(that.data.all_money, "服务消费", that.data.pay_msg.ordersn);//发送微信模板消息
          setTimeout(function () { //跳到该订单详情界面
            wx.redirectTo({
              url: '../my_order/ser_order?ordersn=' + that.data.pay_msg.ordersn
            })
          }, 1000)
        } else if (res.status == "error") {
          app.ispoint = 0;
          app.toast_up(res.mess)
          that.setData({ pwd: '' })
        } else {
          app.ispoint = 0;
          app.modal("错误提示", "网络错误，是否重试？", function (re) {
            if (re) {
              that.input_pwd(e)
            }
          })
        }
      })
    }
  },
  cle:function(e){
    var currentStatu = e.currentTarget.dataset.statu;
    this.util(currentStatu)
  },
  get_ser_msg:function(id){
    app.req("get_service_one.html", {"item_id":id}, function (res) {
      if (res.status == "success") {
          res.mess.ser_num=1                   //服务次数
          res.mess.cat = that.data.my_cat;   //这项服务的所有猫咪
          // res.mess.vip_price = Math.ceil(parseFloat(res.mess.price)*2/3);//会员价
          app.data.ser_selected.push(res.mess);
          that.setData({ service: app.data.ser_selected});
          console.log(app.data.ser_selected);
      } else {
        app.modal("错误提示", "网络错误，是否重试？", function (re) {
          if (re) {
            that.get_ser_msg(id)
          }
        })
      }
    })
  },
  setAll_price:function(){
    console.log(that.data.service)
    var m=0;

    for(var i=0;i<that.data.service.length;i++)
    {
      if (that.data.service[i].cat){
        for (var j = 0; j < that.data.service[i].cat.length; j++) {
          if (that.data.service[i].cat[j].sed && that.data.service[i].cat[j].sed==1){
              if (that.data.islevel == 0) //是不是会员
              {
                m = m + that.data.service[i].price * that.data.service[i].ser_num
              } else { m = m + that.data.service[i].vip_price * that.data.service[i].ser_num }
          }
        }
      }
     
       
      that.setData({all_money:m});
    }
  },
  util: function (currentStatu) {
    that.setData({ pwd: "" }) //将密码制空
    /* 动画部分 */
    // 第1步：创建动画实例 
    var animation = wx.createAnimation({
      duration: 200, //动画时长 
      timingFunction: "linear", //线性 
      delay: 0 //0则不延迟 
    });
    // 第2步：这个动画实例赋给当前的动画实例 
    this.animation = animation;
    // 第3步：执行第一组动画 
    animation.opacity(0).rotateX(-100).step();
    // 第4步：导出动画对象赋给数据对象储存 
    this.setData({
      animationData: animation.export()
    })
    // 第5步：设置定时器到指定时候后，执行第二组动画 
    setTimeout(function () {
      // 执行第二组动画 
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象 
      this.setData({
        animationData: animation
      })
      //关闭 
      if (currentStatu == "close") {
        app.ispoint = 0;
        that.setData({ focus: false })
        this.setData({showModalStatus: false});
      }
    }.bind(this), 200)
    // 显示 
    if (currentStatu == "open") {
      this.setData({showModalStatus: true});
      setTimeout(function () {
        that.setData({ focus: true });//出现输入密码时获取焦点
      }, 550);
    }
  }

})